import Promise from 'promise-polyfill';
import $ from './dom-core.js'
import play from '../assets/play.svg'
import pause from '../assets/pause.svg'
class player {
  constructor(options) {
    this.audio = null
    //拿到传入数据初始化操作
    this.defaultOption = this.opt(options);
    this.fixAudioAttr($(this.defaultOption.container));
    this.renderDom($(this.defaultOption.container));
    //$(this.defaultOption.container).off();
    this.bindEvent($(this.defaultOption.container));
  }
  //初始化合并对象
  opt(options) {
    const defaultOption = {
      container: options.element || document.getElementsByClassName('player')[0],
      url: options.url || '',
      cover: options.cover || '',
    };
    return defaultOption
  }
  /**
     * 格式化播放时间
     * 时间长度，单位秒 
     */
  formatPlayTime(audiotime) {
    var result = '00：00',
      time = parseInt(audiotime),
      hour = parseInt(parseInt(audiotime / 60) / 60),
      min = parseInt(time / 60),
      sec = time % 60;

    if (min >= 60) {
      min = parseInt(min % 60);
    }

    10 > hour && (hour = "0" + hour);
    10 > min && (min = "0" + min);
    10 > sec && (sec = "0" + sec);

    return hour != '00' ? `${hour}:${min}:${sec}` : `${min}:${sec}`;
  }
  /**
    * 渲染播放器DOM
    * @param {Object} $audio jquery对象audio
    */
  renderDom($audio) {
    $audio.html(`<div class="audio-warpper">
                <div class="audio-img">
                    <div class="cover-img">
                    </div>
                </div>
                <div class="audio-paly">
                <div class='play-icon'>
                ${play}
                </div>
                <div class='pause-icon'>
                ${pause}
                </div>
                 </div>
                <div class="rmrb-audio-player">
                    <div class="time-start">00:00</div>
                    <div class="audio-range">
                        <div class="audio-range-totle"></div>
                        <div class="audio-range-preload"></div>
                        <div class="audio-range-progress"></div>
                        <div class="audio-handle-btn"></div>
                    </div>
                    <div class="time-end">00:00</div>
                </div>
            </div>`)
    if (this.defaultOption.cover) {
      let _img = $audio.find('.cover-img')
      let images = new Image()
      images.src = this.defaultOption.cover
      _img.append($(images))
    }

  };
  /**
    * 创建audio对象
    * @param {Object} $audio jquery对象audio
    */
  fixAudioAttr() {
    this.audio = document.createElement('audio');
    this.audio.src = this.defaultOption.url
  };
  /**
    * 给播放器绑定事件
    * @param {Object} $audio jquery对象audio
    */
  bindEvent(audioDom) {
    var $parent = audioDom.find('.audio-warpper'),
      $range = $parent.find('.audio-range'),
      $play = $parent.find('.audio-paly'),
      $handle = $parent.find('.audio-handle-btn'),
      $progress = $parent.find('.audio-range-progress'),
      $bufferd = $parent.find('.audio-range-preload'),
      $timeStart = $parent.find('.time-start'),
      $timeEnd = $parent.find('.time-end'),
      $audioPlayer = $parent.find('.rmrb-audio-player'),
      touching = false,
      total = 0,
      isPlay = false
      ;
    var $audio = $(this.audio);
    $audio[0].onloadedmetadata = () => {
      $timeEnd.text(this.formatPlayTime($audio[0].duration))
      total = $audio[0].duration
    }
    $play.on('click', () => {
      if ($audio[0].paused) {
        $audio[0].play();
        isPlay = true
      } else {
        $audio[0].pause();
        isPlay = false;
      }
    });
    $audio.on('play', function () {
      $play.addClass('play');
    }).on('pause', function () {
      $play.removeClass('play');
    })

    $audio.on('timeupdate', () => {
      //缓冲进度，进度条，总时间  
      var _bufferd = 0,
        _duration = $audio[0].duration,
        _currentTime = $audio[0].currentTime,
        _progress = $audio[0].currentTime / _duration * 100;
      if (!_duration) {
        return;
      }
      if ($audio[0].buffered.length > 0) {
        _bufferd = $audio[0].buffered.end(0) / _duration * 100;
      }
      !touching && $progress.css('width', _progress + '%');
      $bufferd.css('width', _bufferd + '%');
      !touching && $handle.css('left', _progress + '%');
      $timeStart.text(this.formatPlayTime(_currentTime));
      if (_progress == 100) {
        !touching && $handle.css('left', '0%');
        $timeStart.text('00:00');
      }
    });
    $audio.on('error', function () {
      $audio[0].pause();
    });
    // 鼠标按下
    $handle.on('mousedown', function (e) {
      touching = true;
      $audioPlayer.on('mousemove', dragHnadle);
      $(document).on('mouseup', dragUp);
    });

    // 鼠标移动
    var dragHnadle = (e) => {
      if (touching) {
        if (!e.touches) {
          var _x = e.pageX,
            rangeWidth = $range[0].offsetWidth,
            _rleft = $range.offset().elemLeft,
            _l = 0, time = null;
        }
        var _pro = (_x - _rleft) / rangeWidth * 100;
        _l = (_x - _rleft) / rangeWidth;
        if (_pro < 0) _pro = 0;
        if (_pro > 100) _pro = 100;
        if (_l < 0) _l = 0;
        if (_l > 1) _l = 1;
        time = total * _l;
        $progress.css('width', _pro + '%');
        $handle.css('left', _pro + '%');
        $audio[0].pause();
        $audio[0].currentTime = time;
        $timeStart.text(this.formatPlayTime(time));
      }

    };

    var dragUp = (e) => {
      $(document).off('mousemove', dragHnadle);
      touching = false;
      if (isPlay) {
        $audio[0].play();
      }

    };
  };
}
export default player